const listener = new Listener();
const userInfoUrl = "https://gitee.com/lyxfj/userInfo/raw/master/userInfo.json";
const noticeUrl = "https://gitee.com/lyxfj/userInfo/raw/master/notice.json";
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    listener.onMessage(message, sender, sendResponse);
});

listener.setHandle("createSync", (message) => {
    createSync(message.access_token, message.id, (err, result) => {
        chrome.runtime.sendMessage({
            type: "createSyncResult",
            result: result
        });
    });
});

listener.setHandle("getLocalGist", (message, sender, sendResponse) => {
    let gist = getLocalGist();
    sendResponse(gist);
});

listener.setHandle("upload", () => {
    upload((updateTime) => {
        chrome.runtime.sendMessage({
            type: "message",
            message: "已上传"
        });
        chrome.runtime.sendMessage({
            type: "getInfo",
            updateTime: updateTime
        });
    });
});

listener.setHandle("download", () => {
    download((message, updateTime) => {
        chrome.runtime.sendMessage({
            type: "message",
            message: message,
        });
        chrome.runtime.sendMessage({
            type: "getInfo",
            updateTime: updateTime,
            from: "云端"
        });
    });
});

listener.setHandle("setting", (message) => {
    setLocalGist({ [message.key]: message.value });
    const gist = getLocalGist();
    if (["autoDownload", "autoSync"].indexOf(message.key) != -1) {
        // 清除旧的定时器
        clearInterval(gist.timer);
        if (gist.autoDownload || gist.autoSync) {
            // 创建定时任务
            setLocalGist({
                timer: setInterval(download, gist.interval * 1000 || 600000)
            });
        }
    }
});

listener.setHandle("setTimer", (message, sender, sendResponse) => {
    setLocalGist({ interval: message.interval });
    let gist = getLocalGist();
    clearInterval(gist.timer);
    if (gist.autoDownload || gist.autoSync) {
        setLocalGist({
            timer: setInterval(() => {
                download();
            }, gist.interval * 1000)
        });
    }
    sendResponse();
});

listener.setHandle("routerStack", (message) => {
    setLocalGist({ routerStack: message.routerStack });
});

listener.setHandle("login", (message) => {
    Thenjs((cont) => {
        getUserInfo(cont);
    }).then((cont, userInfo) => {
        if (userInfo[message.username]) {
            let list = decrypt(userInfo[message.username], message.username, message.password.repeat(2)).split("[lyx]");
            if (list.length == 2) {
                return createSync(list[1], list[0], (err, result) => {
                    cont(err, result, result ? "" : "id已失效，请重新绑定！");
                });
            }
        }
        cont(null, false, "账号或密码错误！");
    }).then((cont, result, message) => {
        if (result) {
            setLocalGist({
                username: message.username,
                password: message.password,
                isRegist: true,
                first: false,
            });
            let info = getLocalGist();
            info.type = "getInfo";
            chrome.runtime.sendMessage(info);
        }
        chrome.runtime.sendMessage({
            type: "loginResult",
            result: result,
            message: message
        });
    });
});

listener.setHandle("regist", (message) => {
    Thenjs((cont) => {
        getUserInfo(cont);
    }).then((cont, userInfo) => {
        if (userInfo[message.username]) {
            chrome.runtime.sendMessage({
                type: "message",
                message: "该账号已经被注册！"
            });
        }
        else {
            let gist = getLocalGist();
            let data = `${ gist.id }[lyx]${ gist.access_token }`;
            chrome.runtime.sendMessage({
                type: "registResult",
                router: "pay",
                encrypted: encrypt(data, message.username, message.password.repeat(2))
            });
        }
    });
});

listener.setHandle("clear", () => {
    localStorage.removeItem("gistInfo");
    let info = getLocalGist();
    info.type = "getInfo";
    chrome.runtime.sendMessage(info);
    clear();
});

listener.setHandle("notice", () => {
    Thenjs((cont) => {
        getNotice(cont);
    }).then((cont, noticeList) => {
        setLocalGist({ noticeList: noticeList });
        chrome.runtime.sendMessage({
            type: "noticeResult",
            noticeList: noticeList,
        });
    });
});

listener.setHandle("noticeRead", (message) => {
    let gist = getLocalGist();
    gist.noticeRead = gist.noticeRead || {};
    gist.noticeRead[message.id] = true;
    setLocalGist({ noticeRead: gist.noticeRead });
});

listener.setHandle("revert", (message) => {
    let gist = getLocalGist();
    setBookmark(gist.lastBookmarkArray);
    clear();
    chrome.runtime.sendMessage({
        type: "message",
        message: "已恢复！",
    });
});

let updateTime = () => {
    // 更新时间戳
    setLocalGist({
        updateTime: new Date().getTime(),
        from: "本地"
    });
    let gist = getLocalGist();
    if (gist.autoSync || gist.autoUpload) {
        upload();
    }
    console.log("update");
}

function clear() {
    // 书签更新事件
    chrome.bookmarks.onChanged.removeListener(updateTime);

    // 书签创建事件
    chrome.bookmarks.onCreated.removeListener(updateTime);

    // 书签移除事件
    chrome.bookmarks.onRemoved.removeListener(updateTime);

    // 书签移动事件
    chrome.bookmarks.onMoved.removeListener(updateTime);

    // 书签分组更改子结点顺序事件
    chrome.bookmarks.onChildrenReordered.removeListener(updateTime);

    // 书签导入结束事件
    chrome.bookmarks.onImportEnded.removeListener(updateTime);
    
    // 清除定时器
    clearInterval(getLocalGist().timer);

    // 清除本地缓存
    localStorage.removeItem("gistInfo");
}

// 书签更新事件
chrome.bookmarks.onChanged.addListener(updateTime);

// 书签创建事件
chrome.bookmarks.onCreated.addListener(updateTime);

// 书签移除事件
chrome.bookmarks.onRemoved.addListener(updateTime);

// 书签移动事件
chrome.bookmarks.onMoved.addListener(updateTime);

// 书签分组更改子结点顺序事件
chrome.bookmarks.onChildrenReordered.addListener(updateTime);

// 书签导入结束事件
chrome.bookmarks.onImportEnded.addListener(updateTime);

let gist = getLocalGist();

if (gist.autoDownload || gist.autoSync) {
    setLocalGist({
        timer: setInterval(() => {
            download();
        }, gist.interval ? gist.interval * 1000 : 600000)
    });
}
else {
    deleteLocalGistAttribute("timer");
}

function createUser(username, password) {
    let gist = getLocalGist();
    let data = `${ gist.id }[lyx]${ gist.access_token }`;
    return encrypt(data, username, password);
}

function getUserInfo(calllback) {
    new Ajax({
        url: userInfoUrl
    }, (err, body) => {
        try {
            calllback(undefined, JSON.parse(body));
        }
        catch (err) {
            calllback(undefined, {});
        }
    });
}
function getNotice(calllback) {
    new Ajax({
        url: noticeUrl
    }, (err, body) => {
        try {
            calllback(undefined, JSON.parse(body));
        }
        catch (err) {
            calllback(undefined, {});
        }
    });
}
